﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WaterKit.Base
{
    /// <summary>
    /// 字符串操作
    /// </summary>
    public class stringOpr
    {
        /// <summary>
        /// 截取指定数量字符中英混排
        /// </summary>
        /// <param name="str">要截取的字符串变量</param>
        /// <param name="length">要截取的长度</param>
        /// <param name="flag">flag=false表示不需要加省略号</param>
        /// <returns></returns>
        public static string GetSubString(string str, int length,string endStr)
        {
            string temp = str.Substring(0, (str.Length < length + 1) ? str.Length : length + 1);
            byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);

            string outputStr = "";
            int count = 0;

            for (int i = 0; i < temp.Length; i++)
            {
                if ((int)encodedBytes[i] == 63)
                    count += 2;
                else
                    count += 1;

                if (count <= length - endStr.Length)
                    outputStr += temp.Substring(i, 1);
                else if (count > length)
                    break;
            }

            if (count <= length)
            {
                outputStr = temp;
                endStr = "";
            }

            outputStr += endStr;

            return outputStr;
        }
    }
}
